package com.sqoop.core.MsgFutrue;

import com.sqoop.core.request.Request;
import com.sqoop.core.request.Response;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by zw on 2017/11/6.
 */
public class MsgFutrue implements IMsgFutrue{

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    private Request request;
    private Response response;

    public MsgFutrue(Request request) {
        this.request = request;
    }

    @Override
    public void done(Response response) {
        this.response = response;
        countDownLatch.countDown();
        return;
    }

    @Override
    public int getTimeout() {
        return 0;
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
       throw new RuntimeException("not handle this method!!!");
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return countDownLatch.getCount() == 0;
    }

    @Override
    public Response get() throws InterruptedException, ExecutionException {
        countDownLatch.await();
        return response;
    }

    @Override
    public Response get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        countDownLatch.await(timeout,unit);
        return response;
    }
}